package com.lge.test;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.json.simple.ItemList;
import org.json.simple.JSONObject;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.lge.yelp.Yelp;
import com.lge.yelp.YelpBusiness;
import com.lge.yelp.YelpSearchResult;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class YelpTask extends AsyncTask<String, Void, List<YelpBusiness>> {

	private MainActivity context;
	private ImageView rate;
	
	public YelpTask (MainActivity context, View rate) {
		this.rate = (ImageView) rate;
		this.context = context;
	}
	
	@Override
	protected List<YelpBusiness> doInBackground(String... terms) {
		Yelp yelp = new Yelp();
		String response = yelp.search(terms[0], context.getLocation().getLatitude(), context.getLocation().getLongitude());
		
		Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
		YelpSearchResult places = gson.fromJson(response, YelpSearchResult.class);
	    List<YelpBusiness> restaraunts = null;
	    if (places != null) {
	    	restaraunts = places.getBusinesses();
		    
		    for (int x=0; x<restaraunts.size(); x++) {
		    	restaraunts.get(x).setBitmapImg();
		    }
	    }
		
		return restaraunts;
	}
	
	protected void onPostExecute(List<YelpBusiness> response) {
	    if (response == null) {
	    	rate.setImageResource(R.drawable.noconn);
	    	return;
	    }
	    if (response.size() > 0) {
	    	rate.setImageBitmap(response.get(0).getBitmapImg());
	    }
	}

}
